package com.ch.clinking.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.Utils.TimeUtil;
import com.ch.clinking.ViewHolder.MerListViewHolder;
import com.ch.clinking.activity.AddOrderActivity;
import com.ch.clinking.activity.EditMerStockActivity;
import com.ch.clinking.bean.Merchandise;
import com.ch.clinking.bean.MerchandiseDto;
import com.ch.clinking.bean.Order;
import com.google.gson.Gson;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class MerListViewAdapter  extends RecyclerView.Adapter<MerListViewHolder>{

    private List<MerchandiseDto> merchandiseList;
    private Activity context;
    private ProgressBar progressBar;

    boolean color = true;

    private ActivityResultLauncher<Intent> resultLauncher;

    public void setResultLauncher(ActivityResultLauncher<Intent> resultLauncher) {
        this.resultLauncher = resultLauncher;
    }

    public MerListViewAdapter(@NonNull Activity context, List<MerchandiseDto> merchandiseList, ProgressBar progressBar) {
        this.merchandiseList = merchandiseList;
        this.progressBar = progressBar;
        this.context = context;
    }


    @NonNull
    @Override
    public MerListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_spu_layout, parent, false);
        return new MerListViewHolder(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull MerListViewHolder holder, int position) {
        MerchandiseDto merchandise = merchandiseList.get(position);


        // 设置数据
        holder.merTitle.setText(merchandise.getTitle());
        holder.merSKCId.setText(merchandise.getSkcId());
        holder.merSPUId.setText(merchandise.getSpuId());
        holder.productNum.setText(merchandise.getProductNumber());

        // 清空表格内容
        holder.tableLayout.removeAllViews();

        // 动态生成表格内容
        getSize(merchandise, holder.tableLayout);


//        getOrderInfoTagList(merchandise.getSkcId(), holder.circleContainer);

        // 动态添加圆圈
        addCircleTextViews(merchandise.getOrderList(), holder.circleContainer);



        // 设置默认占位图片
        Glide.with(context)
                .load(R.drawable.appicon)
                .into(holder.merImg);

        // 加载图片
        Glide.with(context)
                .load(OkHttpUtil.getInstance().getIMG_URL() + merchandise.getFirstImage())
                .placeholder(R.drawable.appicon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略：缓存原始图片和转换后的图片
                .thumbnail(0.5f)  // 缩略图大小
                .error(R.drawable.appicon)
                .into(holder.merImg);

        // 设置点击事件
        holder.listMerItemContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, EditMerStockActivity.class);
                intent.putExtra("skcId", merchandise.getSkcId());
                resultLauncher.launch(intent);
//                context.startActivity(intent);
            }
        });

        holder.oderMake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AddOrderActivity.class);
                intent.putExtra("skcId", merchandise.getSkcId());
                resultLauncher.launch(intent);
            }
        });

    }

    public void updateMerStock(MerchandiseDto merchandiseUpdateStock) {
        for (MerchandiseDto mer : merchandiseList) {
            if (mer.getSkcId().equals(merchandiseUpdateStock.getSkcId())) {
                int index = merchandiseList.indexOf(mer);
                merchandiseList.set(index, merchandiseUpdateStock);
                notifyItemChanged(index);
            }
        }
    }


    private void getOrderInfoTagList(String skcId, LinearLayout circleContainer) {

        showLoading();

        // 获取订单TAG列表
        HashMap<String, String> skcIdInfo = new HashMap<>();
        skcIdInfo.put("skcId", skcId);

        OkHttpUtil.getInstance().doPostForm("/order/selectOrderTag", new DoCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(String result) {
                Log.d("selectOrderTag", "result:"+result);

                Order[] orderArray = new Gson().fromJson(result, Order[].class);
                List<Order> orderList = Arrays.asList(orderArray);

                // 动态添加圆圈
                addCircleTextViews(orderList, circleContainer);


                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(context, "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, skcIdInfo);
    }

    @Override
    public int getItemCount() {
        return merchandiseList.size();
    }

    @SuppressLint("SetTextI18n")
    private void getSize(MerchandiseDto merchandise, TableLayout tableLayout) {
        color = true;
        TableRow sizeRow = new TableRow(context);
        TableRow stockRow = new TableRow(context);
        sizeRow.setPadding(0, 0, 0, 0);
        stockRow.setPadding(0, 0, 0, 0);
        TableRow.LayoutParams editTextParams = new TableRow.LayoutParams(120, TableRow.LayoutParams.MATCH_PARENT);
        editTextParams.gravity = Gravity.CENTER;

        if (merchandise.isActivate_XXS()) {
            TextView size = new TextView(context);
            size.setText("XXS");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XXS()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_XS()) {
            TextView size = new TextView(context);
            size.setText("XS");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XS()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_S()) {
            TextView size = new TextView(context);
            size.setText("S");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_S()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_M()) {
            TextView size = new TextView(context);
            size.setText("M");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_M()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_L()) {
            TextView size = new TextView(context);
            size.setText("L");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_L()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_XL()) {
            TextView size = new TextView(context);
            size.setText("XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_XXL()) {
            TextView size = new TextView(context);
            size.setText("XXL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XXL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_0XL()) {
            TextView size = new TextView(context);
            size.setText("0XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_0XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_1XL()) {
            TextView size = new TextView(context);
            size.setText("1XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_1XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_2XL()) {
            TextView size = new TextView(context);
            size.setText("2XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_2XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_3XL()) {
            TextView size = new TextView(context);
            size.setText("3XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_3XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_4XL()) {
            TextView size = new TextView(context);
            size.setText("4XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_4XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_5XL()) {
            TextView size = new TextView(context);
            size.setText("5XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_5XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_6XL()) {
            TextView size = new TextView(context);
            size.setText("6XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_6XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }

        tableLayout.addView(sizeRow);
        tableLayout.addView(stockRow);
    }

    private void setTableLayout(TextView size, TextView stock, TableRow sizeRow, TableRow stockRow, TableRow.LayoutParams editTextParams) {
        size.setLayoutParams(editTextParams);
        stock.setLayoutParams(editTextParams);
        size.setBackgroundColor(getCellColor());
        stock.setBackgroundColor(getCellColor());
        if (color) {
            color = false;
        } else {
            color = true;
        }
        size.setWidth(120);
        stock.setWidth(120);
        size.setPadding(0, 0, 0, 0);
        stock.setPadding(0, 0, 0, 0);
        size.setGravity(Gravity.CENTER);
        stock.setGravity(Gravity.CENTER);
        sizeRow.addView(size);
        stockRow.addView(stock);
    }

    private int getCellColor() {
        if (color) {
            return Color.parseColor("#E7E7E7"); // 偶数索引
        } else {
            return Color.parseColor("#FFFFFF"); // 奇数索引
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void addCircleTextViews(List<Order> values, LinearLayout circleContainer) {
        circleContainer.removeAllViews();
        int diameter = 70;  // 圆形的直径，可以根据需要调整

        for (Order order : values) {
            TextView textView = new TextView(context);
            textView.setText(order.getCreatedTime().substring(8, 10));
            textView.setTextColor(context.getResources().getColor(android.R.color.white));
            textView.setTextSize(11);

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopup(v, "This is a message for " + ((TextView)v).getText().toString());
                }
            });

            Log.d("OrderTag", "refreshMerchandiseList"+order.getCreatedTime());

            long day = (int)TimeUtil.getDayNum(order.getCreatedTime());



            // 设置圆形背景
            GradientDrawable background = new GradientDrawable();

            // 背景颜色
            if (day <= 3) {
                background.setColor(context.getResources().getColor(R.color.order_state_yes));
            } else if (day <= 5) {
                background.setColor(context.getResources().getColor(R.color.order_state_orange));
            } else if (day <= 7) {
                background.setColor(context.getResources().getColor(R.color.order_state_no_bg));
            } else {
                background.setColor(context.getResources().getColor(R.color.black));
            }

            background.setShape(GradientDrawable.OVAL); // 圆形
            background.setSize(diameter, diameter); // 设置宽度和高度相等
            textView.setBackground(background);

            // 设置内边距
            int padding = 10;
            textView.setPadding(padding, padding, padding, padding);

            // 设置TextView的宽度和高度相等
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(diameter, diameter);
            params.setMargins(10, 0, 10, 0); // 设置间距
            textView.setLayoutParams(params);

            // 设置TextView的重力居中
            textView.setGravity(Gravity.CENTER);

            circleContainer.addView(textView);
        }
    }

    private void showPopup(View anchorView, String message) {
        // 加载气泡布局
        View popupView = LayoutInflater.from(context).inflate(R.layout.bubble_mer_order_message, null);

        // 设置消息内容
        TextView messageTextView = popupView.findViewById(R.id.messageTextView);
        messageTextView.setText(message);

        // 创建PopupWindow
        final PopupWindow popupWindow = new PopupWindow(popupView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        // 显示PopupWindow
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

        // 计算弹窗位置
        int[] location = new int[2];
        anchorView.getLocationOnScreen(location);

        // 在TextView上方显示PopupWindow
        popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY,
                location[0] - (popupWindow.getWidth() - anchorView.getWidth()) / 2,
                location[1] - popupWindow.getHeight());
    }

    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        if (context != null) {
            context.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
        if (context != null) {
            context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

}
